const vscode = require('vscode');
const fs = require('fs');
const path = require('path');
const net = require('net');
const { exec } = require('child_process');

// 创建日志输出通道
let outputChannel;
let tcpServer;
let connectedClients = new Set();

const TCP_PORT = 9206;

// 创建TCP服务器
function createTcpServer() {
    tcpServer = net.createServer((socket) => {
        outputChannel.appendLine('[Cursor Sync] 新的TCP连接已建立');
        connectedClients.add(socket);

        socket.on('data', (data) => {
            try {
                const message = JSON.parse(data.toString());
                handleReceivedMessage(message);
            } catch (error) {
                outputChannel.appendLine(`[Cursor Sync] 解析消息失败: ${error.message}`);
            }
        });

        socket.on('error', (error) => {
            outputChannel.appendLine(`[Cursor Sync] TCP连接错误: ${error.message}`);
            connectedClients.delete(socket);
        });

        socket.on('close', () => {
            outputChannel.appendLine('[Cursor Sync] TCP连接已关闭');
            connectedClients.delete(socket);
        });
    });

    tcpServer.listen(TCP_PORT, '127.0.0.1', () => {
        outputChannel.appendLine(`[Cursor Sync] TCP服务器已启动，监听端口: ${TCP_PORT}`);
    });

    tcpServer.on('error', (error) => {
        outputChannel.appendLine(`[Cursor Sync] TCP服务器错误: ${error.message}`);
    });
}

// 发送消息
function sendMessage(message) {
    if (connectedClients.size === 0) {
        outputChannel.appendLine('[Cursor Sync] 没有连接的客户端，无法发送消息');
        return;
    }

    try {
        const data = JSON.stringify(message) + '\n'; // 添加换行符作为消息结束标记
        for (const client of connectedClients) {
            if (client.writable) {
                const canContinue = client.write(data);
                if (!canContinue) {
                    // 如果缓冲区已满，等待drain事件
                    client.once('drain', () => {
                        outputChannel.appendLine('[Cursor Sync] 缓冲区已清空，可以继续发送数据');
                    });
                }
            }
        }
        outputChannel.appendLine('[Cursor Sync] 消息发送成功');
    } catch (error) {
        outputChannel.appendLine(`[Cursor Sync] 发送消息失败: ${error.message}`);
    }
}

// 处理接收到的消息
async function handleReceivedMessage(message) {
    try {
        const { file_path, line_number, column } = message;
        if (!file_path || !line_number || !column) {
            outputChannel.appendLine('[Cursor Sync] 消息格式错误：缺少必要字段');
            return;
        }

        // 打开文件并定位到指定位置
        await openFileAtPosition(file_path, line_number, column);
        
        // 将窗口置顶
        await vscode.commands.executeCommand('workbench.action.focusActiveEditorGroup');
        outputChannel.appendLine('[Cursor Sync] 窗口已置顶');
    } catch (error) {
        outputChannel.appendLine(`[Cursor Sync] 处理消息失败: ${error.message}`);
    }
}

// 打开指定文件位置
async function openFileAtPosition(filePath, lineNumber, column) {
    try {
        // 验证文件路径
        if (!filePath || !fs.existsSync(filePath)) {
            throw new Error('无效的文件路径');
        }

        // 转换为绝对路径
        const absolutePath = path.resolve(filePath);
        
        // 打开文件
        const document = await vscode.workspace.openTextDocument(absolutePath);
        const editor = await vscode.window.showTextDocument(document);
        
        // 设置光标位置
        const position = new vscode.Position(
            Math.max(0, lineNumber - 1),
            Math.max(0, column - 1)
        );
        
        // 设置选择范围
        editor.selection = new vscode.Selection(position, position);
        
        // 确保光标位置可见
        editor.revealRange(
            new vscode.Range(position, position),
            vscode.TextEditorRevealType.InCenter
        );
        
        outputChannel.appendLine(`[Cursor Sync] 已打开文件: ${absolutePath}:${lineNumber}:${column}`);
        return true;
    } catch (error) {
        outputChannel.appendLine(`[Cursor Sync] 打开文件失败: ${error.message}`);
        return false;
    }
}

// 更新状态并发送
function updateAndSendState() {
    try {
        const editor = vscode.window.activeTextEditor;
        if (!editor) {
            outputChannel.appendLine('[Cursor Sync] 没有活动的编辑器');
            return;
        }
        
        const document = editor.document;
        if (!document) {
            outputChannel.appendLine('[Cursor Sync] 没有活动的文档');
            return;
        }
        
        const position = editor.selection.active;
        if (!position) {
            outputChannel.appendLine('[Cursor Sync] 没有光标位置');
            return;
        }
        
        const state = {
            file_path: document.fileName,
            line_number: position.line + 1,
            column: position.character + 1,
            timestamp: new Date().toISOString()
        };

        sendMessage(state);
    } catch (error) {
        outputChannel.appendLine(`[Cursor Sync] 更新状态失败: ${error.message}`);
    }
}

// 插件激活函数
function activate(context) {
    try {
        // 创建输出通道
        outputChannel = vscode.window.createOutputChannel('Cursor Sync');
        outputChannel.appendLine('插件开始激活...');
        
        // 创建TCP服务器
        createTcpServer();
        
        // 注册F4快捷键命令
        let f4Command = vscode.commands.registerCommand('cursor-sync-plugin.f4Trigger', () => {
            try {
                outputChannel.appendLine('F4命令被触发');
                const editor = vscode.window.activeTextEditor;
                if (!editor) {
                    outputChannel.appendLine('没有活动的编辑器');
                    return;
                }
                
                const document = editor.document;
                const position = editor.selection.active;
                
                // 获取配置的Eclipse路径
                const config = vscode.workspace.getConfiguration('cursor-sync-plugin');
                const eclipsePath = config.get('eclipsePath', 'D:\\eclipse2024\\jee-2024-12\\eclipse\\eclipse.exe');
                
                // 构建Eclipse命令行参数
                const filePath = document.fileName;
                const lineNumber = position.line + 1;
                const column = position.character + 1;
                
                // 使用child_process执行Eclipse命令
                const command = `"${eclipsePath}" --launcher.openFile "${filePath}:${lineNumber}:${column}"`;
                
                exec(command, (error, stdout, stderr) => {
                    if (error) {
                        outputChannel.appendLine(`执行Eclipse命令失败: ${error.message}`);
                        return;
                    }
                    if (stderr) {
                        outputChannel.appendLine(`Eclipse命令错误输出: ${stderr}`);
                        return;
                    }
                    outputChannel.appendLine(`Eclipse命令执行成功 - "${eclipsePath}" --launcher.openFile "${filePath}:${lineNumber}:${column}"`);
                });
            } catch (error) {
                outputChannel.appendLine(`F4命令执行失败: ${error.message}`);
            }
        });
        
        // 注册清理回调
        context.subscriptions.push(f4Command);
        
        outputChannel.appendLine('插件初始化成功');
    } catch (error) {
        outputChannel.appendLine(`[Cursor Sync] 插件激活失败: ${error}`);
        throw error;
    }
}

// 插件停用函数
function deactivate() {
    try {
        if (tcpServer) {
            tcpServer.close();
        }
        // 关闭所有客户端连接
        for (const client of connectedClients) {
            client.destroy();
        }
        connectedClients.clear();
        if (outputChannel) {
            outputChannel.appendLine('插件已停用');
            outputChannel.dispose();
        }
    } catch (error) {
        outputChannel.appendLine(`[Cursor Sync] 停用插件时发生错误: ${error}`);
    }
}

module.exports = {
    activate,
    deactivate
};